package com.hncj.controller;

import com.hncj.pojo.User;
import com.hncj.result.R;
import com.hncj.service.ImageService;
import com.hncj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/user")
public class userController {

    @Autowired
    private UserService userService;
    @Autowired
    private imageController imageControl;
    @Autowired
    private ImageService imageService;

    private void userName(User byId) {
        System.out.println("用户原有数据:"+byId);
        if(byId.getImage() != null&&byId.getImage().trim().length()>0){
            String[] split = byId.getImage().split("/");
            String[] name = new String[1];
            name[0]=split[split.length - 1];
            imageControl.deleteImageByName(name);
        }
    }

    @DeleteMapping
    public R<String> deleteUser(@RequestBody int[] ids){

        for(int i : ids) {
            User byId = userService.getById(i);

            userName(byId);

            userService.removeById(i);
        }

        return R.success("删除成功!");
    }

    @GetMapping//返回user的id
    public R<Integer> loginUser(@RequestParam("username") String username,@RequestParam("password") String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int byUsername = userService.getByUsername(user);

        if(byUsername == -1) return R.error("未找到该用户名！");
        else if(byUsername == -2) return R.error("密码错误！");
        return R.success(byUsername);
    }

    @GetMapping("/list")
    public R<List<User>> getList(){
        return R.success(userService.list());
    }

    @PostMapping//返回新建user的id
    public R<Integer> registerUser(@RequestBody User user){
        return R.success(userService.setByUser(user));
    }

    @GetMapping("/{id}")//返回user
    public R<User> getById(@PathVariable("id") Integer id){
        return R.success(userService.getById(id));
    }

    @PutMapping
    public R<Object> updateUser(@RequestBody User user){

        if(user.getImage()!=null&&user.getImage().trim().length()>0){
            User byId = userService.getById(user.getId());
            userName(byId);
        }

        return R.success(userService.updateById(user)?user:"更新失败");
    }

    @PutMapping("/password")
    public R<String> updatePassword(Integer id,String old,String last){
        System.out.println("id:"+id);

        User data = getById(id).getData();

        if(Objects.equals(data.getPassword(), old)){
            User user=new User();
            user.setId(id);
            user.setPassword(last);
            user.setLevel(data.isLevel());

            return R.success(userService.updateById(user)?"更新成功":"更新失败");
        }

        return R.error("密码错误！");
    }

}
